﻿using NUnit.Framework;

namespace WordStudy20250123.Other
{
    [TestFixture]
    public class Other002
    {

        [Test]
        public void Test01()
        {
            var values = new List<double?> { 2, 7, 25, 6.5, 5.5, 4.8, 7.2, 8.9, double.NaN, double.NaN, double.NaN, double.NaN, 5.8, 4.8, 7.2, 6.9, 6.3, 8.9, 9.3, 4.9,
                                        8.2, 4, 8, 6.5, 5.5, 4.8, 7.6, 8.9, 6.3, double.NaN, double.NaN, 6.5, 5.8, 7.8, 7.2, 6.9, 6.0, 8.9, 5.3, 7.9 };
            double avg = SplitCalcAvg(values, 10);
            Console.WriteLine("平均值: " + avg);
        }

        /// <summary>
        /// 计算 double? 集合的平均值，分片处理，空值按0处理，避免溢出
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <param name="block">分片大小</param>
        /// <returns>平均值</returns>
        public double SplitCalcAvg(List<double?> datas, int block = 10000)
        {
            if (datas == null || datas.Count == 0) return 0;

            long totalCount = datas.Count;
            decimal avg = 0m;

            for (int i = 0; i < datas.Count; i += block)
            {
                int count = Math.Min(block, datas.Count - i);
                decimal blockSum = 0m;
                for (int j = 0; j < count; j++)
                {
                    double? val = datas[i + j];
                    blockSum += (decimal)((val.HasValue && !double.IsNaN(val.Value)) ? val.Value : 0.0);
                }
                avg += (blockSum / totalCount);
            }

            return (double)avg;
        }
    }
}
